<template>
    <div>
        <OAMain title="员工列表">
            <el-card>
                <el-form :inline="true" class="filter-form">
                    <el-form-item label="按部门">
                        <el-select v-model="filterForm.department_id" placeholder="请选择请假类型">
                            <el-option v-for="department in departments" :label="department.name" :value="department.id"
                                :key="department.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="按姓名">
                        <el-input v-model="filterForm.realname" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="按日期">
                        <el-date-picker v-model="filterForm.date_joined" type="daterange" unlink-panels
                            range-separator="到" start-placeholder="起始日期" end-placeholder="结束日期" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="search" type="primary" @click="onSearch"></el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="download" type="danger" @click="onDownload">下载</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-upload
                            :action="uploadUrl"
                            :on-success="onUploadSuccess"
                            :on-error="onUploadError"
                            :headers="{
                                'Authorization':'JWT '+authStore.token
                            }"
                            :show-file-list="false"
                            :auto-upload="true"
                            accept=".xlsx,.xls,.csv">
                            <el-button type="success" icon="upload">上传</el-button>
                            <!-- <template #tip>
                                <div class="el-upload__tip">
                                    jpg/png files with a size less than 500KB.
                                </div>
                            </template> -->
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-card>

            <el-card>
                <el-table :data="staffs" ref="tableRef">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="序号" width="60">
                        <template #default="scope">{{ scope.$index + 1 }}</template>
                    </el-table-column>
                    <el-table-column label="姓名" prop="realname"></el-table-column>
                    <el-table-column label="邮箱" prop="email"></el-table-column>
                    <el-table-column label="入职时间">
                        <template #default="scope">
                            {{ timeFormatter.stringFromDateTime(scope.row.date_joined) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="部门" prop="department.name"></el-table-column>
                    <el-table-column label="状态">
                        <template #default="scope">
                            <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
                            <el-tag v-else-if="scope.row.status == 2" type="warning">未激活</el-tag>
                            <el-tag v-else type="danger">已锁定</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button type="primary" icon="Edit" circle @click="onEidtStaff(scope.$index)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <template #footer>
                    <div style="display: flex; justify-content: space-between;">
                        <el-form-item label="每页：">
                            <el-select v-model="page_size" size="small" style="width: 100px;">
                                <el-option select label="10条/页" :value="10" />
                                <el-option label="20条/页" :value="20" />
                            </el-select>
                        </el-form-item>
                        <el-pagination background layout="prev, pager, next" :total="pagination.total"
                            v-model:currentPage="pagination.page" :page-size="page_size" />
                    </div>
                </template>
            </el-card>
        </OAMain>

        <OADialog title="编辑员工" v-model="dialogVisible" @submit="onSubmitStaff">
            <el-form :model="form">
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-radio-group v-model="form.status">
                        <el-radio :value="1">激活</el-radio>
                        <el-radio :value="3">锁定</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </OADialog>
    </div>
</template>

<script setup name="StaffList">
import OAMain from "@/components/OAMain.vue";
import OADialog from "@/components/OADialog.vue";
import OAPagination from "@/components/OAPagination.vue";
import timeFormatter from "@/utils/timeFormatter"
import { ref, reactive, onMounted, watch } from "vue";
import staffHttp from "@/api/staffHttp";
import { ElMessage } from "element-plus";
import { useAuthStore } from "@/stores/auth";

const authStore = useAuthStore();


let baseURL = import.meta.env.VITE_BASE_URL;
let uploadUrl = baseURL + "/staff/upload";

let staffs = ref([]);

let page_size = ref(10);
const pagination = reactive({
    page: 1,
    total: 0,
});

const fetchStaff = async (page, page_size) => {
    try {
        let data = await staffHttp.getStaffList(page, page_size,filterForm);
        staffs.value = data.results;
        pagination.total = data.count;
        pagination.page = page
    } catch (detail) {
        ElMessage.error(detail);
    }
};

watch(() => pagination.page, async (value) => {
    await fetchStaff(value, page_size.value);
});

watch(page_size, async (value) => {
    if (pagination.page == 1) {
        fetchStaff(1, value);
    } else {
        pagination.page = 1;
    }
})

let handleIndex = 0;
const onEidtStaff = (index) => {
    handleIndex = index;
    dialogVisible.value = true;
    let staff = staffs.value[index];
    form.status = staff.status;
}

let dialogVisible = ref(false);
let formLabelWidth = "100px";
const form = reactive({
    status: 1,
});


const onSubmitStaff = async () => {
    let staff = staffs.value[handleIndex];
    console.log(staff)
    try {
        let newStaff = await staffHttp.updateStaffIndex(staff.uid, form.status);
        staffs.value.splice(handleIndex, 1, newStaff)
        ElMessage.success("修改成功");
    } catch (detail) {
        ElMessage.error(detail);
    }
    dialogVisible.value = false;
};

let filterForm = reactive({
    department_id: null,
    realname: "",
    date_joined: [],
})
let departments = ref([]);

const onSearch = async () => {
    await fetchStaff(1, page_size.value);
    console.log(filterForm)
};

let tableRef = ref(null);

const onDownload = async () => {
    let rows = tableRef.value.getSelectionRows()
    if(rows.length == 0 ||! rows){
        ElMessage.info("请选择需要下载的员工");
        return;
    }
    try{
        let response = await staffHttp.downloadStaffs(rows.map(row => row.uid));
        let href = URL.createObjectURL(response.data)
        const a = document.createElement('a')
        a.href = href
        a.setAttribute('download', '员工信息.xlsx')
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(href)
    }catch(detail){
        ElMessage.error(detail);
    }
};

const onUploadSuccess = async () => {
    ElMessage.success("上传成功");
    await fetchStaff(1, page_size.value);
};

const onUploadError = (error) => {
    const detail = JSON.parse(error.message).detail
    ElMessage.error(detail);
}

onMounted(async () => {
    await fetchStaff();
    try {
        let data = await staffHttp.getAllDepartment();
        departments.value = data.results;
    } catch (detail) {
        ElMessage.error(detail);
    }
})
</script>

<style scoped>
.filter-form .el-input {
    --el-input-width: 140px;
}

.filter-form .el-select {
    --el-select-width: 140px;
}

.filter-form .el-form-item {
    margin-right: 20px;
}
</style>